<?php
require_once('BaseController.php');
/**
 * Login no sistema
 * @author Gedalias
 * @name Login
 */
class Third_LoginController extends BaseController
{
	protected $name = 'login';
	protected $configFile = 'third_login';

	/**
	 * Efetuar login
	 * @return unknown_type
	 */
	public function indexAction()
	{
		if( $this->getRequest()->isPost() && ( $this->_site ) ){
			$login = $this->getRequest()->getParam('login', NULL);
			$senha = $this->getRequest()->getParam('senha', NULL);

			//INFOS DA OPERACAO
			$operationOptions = array(
	    		'operacao'=>'login',
	    		'site_id'=>$this->_site['id'],
	    		'pagina'=> 0,
	    		'tabelas'=> array('login')
	    	);

			$autentication = $this->_auth->authenticate( $login, $senha );
			if( $autentication ){
				//VERIFICA STATUS
				if( $autentication->status == 1 ){
					//VERIFICA TIPO
					switch( $autentication->tipo ){
						case 'sistema':
						case 'sistema_cliente':
							if( $autentication->sites_id == $this->_site['id'] ){
								if ( $this->getRequest()->isXmlHttpRequest() ) {
									echo true;
								} else{
									$this->flash('teste','/third/dashboard');
								}
							} else {
								define('LOGIN_ERROR_CODE', '4');
								define('LOGIN_ERROR', 'USER_NOT_ALLOWED_TO_THIS_SITE');
							}
						break;
						default:
							define('LOGIN_ERROR_CODE', '3');
							define('LOGIN_ERROR', 'USER_NOT_ALLOWED_TO_THIRD');
						break;
					}
				} else{
					define('LOGIN_ERROR_CODE', '2');
					define('LOGIN_ERROR', 'USER_DELETED_OR_DISABLED');
				}
			} else {
				define('LOGIN_ERROR_CODE', '1');
				define('LOGIN_ERROR', 'INVALID_CREDENTIALS');
			}
		} else {
			define('LOGIN_ERROR_CODE', '0');
			define('LOGIN_ERROR', 'INVALID_REQUEST_OR_SITE_URL');
		}

		//LOG EVENT
		if(defined('LOGIN_ERROR')){
			$message = LOGIN_ERROR;
			echo 0;
		} else {
			$message = 'SUCESS';
		}
		$this->log('login', $message );

		if ( $message != 'SUCCESS' && !$this->getRequest()->isXmlHttpRequest() ) {
				$this->flash('login_error','/third/');
		}
		
		$this->disableViewRender();
	}

	/**
	 * Sair do Sistema
	 */
	function logoutAction(){
		//LIMPA SECAO LOGADA ANTERIORMENTE
        $this->_auth->logout();
        $this->log('login', 'SUCCESS' );
        
        $this->flash('Deslogado com sucesso.', 'success', '/third/' );
	}
}

